<template>
  <div class="teacher-courses">
    <div class="page-header">
      <h1>我的授课</h1>
      <p>管理您教授的课程和学生</p>
    </div>

    <!-- 统计信息 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon courses">
              <el-icon><Reading /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.totalCourses }}</h3>
              <p>授课数量</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon students">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.totalStudents }}</h3>
              <p>学生总数</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon credits">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.totalCredits }}</h3>
              <p>授课学分</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon capacity">
              <el-icon><PieChart /></el-icon>
            </div>
            <div class="stat-info">
              <h3>{{ stats.averageEnrollment }}%</h3>
              <p>平均选课率</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 课程列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>课程列表</span>
          <div>
            <el-button type="primary" @click="handleRefresh" :icon="Refresh" size="small">
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="courses" v-loading="loading" @row-click="handleRowClick">
        <el-table-column prop="code" label="课程代码" width="120" />
        <el-table-column prop="name" label="课程名称" min-width="200">
          <template #default="scope">
            <div class="course-info">
              <div class="course-name">{{ scope.row.name }}</div>
              <div class="course-desc" v-if="scope.row.description">
                {{ scope.row.description }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="credit" label="学分" width="80" align="center" />
        <el-table-column label="选课情况" width="150">
          <template #default="scope">
            <div class="enrollment-info">
              <span>{{ scope.row.current_enrollment || 0 }}/{{ scope.row.capacity }}</span>
              <el-progress 
                :percentage="getEnrollmentPercentage(scope.row)" 
                :stroke-width="4"
                :show-text="false"
                style="margin-top: 4px"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="getStatusType(scope.row)"
              size="small"
            >
              {{ getStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click.stop="handleViewStudents(scope.row)"
            >
              查看学生
            </el-button>
            <el-button
              type="success"
              size="small"
              @click.stop="handleGradeManagement(scope.row)"
            >
              成绩管理
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 学生列表对话框 -->
    <el-dialog
      v-model="studentDialog.visible"
      :title="studentDialog.title"
      width="800px"
    >
      <el-table :data="studentDialog.students" v-loading="studentDialog.loading">
        <el-table-column prop="student_id" label="学号" width="120" />
        <el-table-column prop="student_name" label="姓名" width="120" />
        <el-table-column prop="student_username" label="用户名" width="120" />
        <el-table-column prop="selection_date" label="选课时间" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.selection_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="grade" label="成绩" width="100">
          <template #default="scope">
            <el-tag 
              v-if="scope.row.grade"
              :type="getGradeType(scope.row.grade)"
              size="small"
            >
              {{ scope.row.grade }}
            </el-tag>
            <span v-else class="no-grade">未录入</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag 
              :type="getStudentStatusType(scope.row.status)"
              size="small"
            >
              {{ getStudentStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="studentDialog.visible = false">关闭</el-button>
          <el-button type="primary" @click="handleExportStudentList">
            导出名单
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 成绩管理对话框 -->
    <el-dialog
      v-model="gradeDialog.visible"
      :title="gradeDialog.title"
      width="900px"
    >
      <div class="grade-management">
        <div class="grade-actions">
          <el-button type="success" @click="handleBatchGrade" :icon="Edit">
            批量录入
          </el-button>
          <el-button type="primary" @click="handleImportGrades" :icon="Upload">
            导入成绩
          </el-button>
          <el-button @click="handleExportGrades" :icon="Download">
            导出成绩
          </el-button>
        </div>

        <el-table :data="gradeDialog.students" v-loading="gradeDialog.loading">
          <el-table-column prop="student_id" label="学号" width="120" />
          <el-table-column prop="student_name" label="姓名" width="120" />
          <el-table-column label="成绩" width="150">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.grade"
                :min="0"
                :max="100"
                :precision="1"
                size="small"
                @change="handleGradeChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="等级" width="100">
            <template #default="scope">
              <el-tag 
                v-if="scope.row.grade"
                :type="getGradeType(scope.row.grade)"
                size="small"
              >
                {{ getGradeLevel(scope.row.grade) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag 
                :type="scope.row.gradeChanged ? 'warning' : 'success'"
                size="small"
              >
                {{ scope.row.gradeChanged ? '待保存' : '已保存' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button
                v-if="scope.row.gradeChanged"
                type="primary"
                size="small"
                @click="handleSaveGrade(scope.row)"
              >
                保存
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="gradeDialog.visible = false">关闭</el-button>
          <el-button type="primary" @click="handleSaveAllGrades">
            保存全部
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量录入成绩对话框 -->
    <el-dialog
      v-model="batchGradeDialog.visible"
      title="批量录入成绩"
      width="400px"
    >
      <el-form :model="batchGradeForm" label-width="80px">
        <el-form-item label="统一成绩">
          <el-input-number
            v-model="batchGradeForm.grade"
            :min="0"
            :max="100"
            :precision="1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="适用范围">
          <el-checkbox-group v-model="batchGradeForm.applyTo">
            <el-checkbox label="ungraded">仅未录入成绩的学生</el-checkbox>
            <el-checkbox label="all">所有学生</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchGradeDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmBatchGrade">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Reading, 
  UserFilled, 
  Trophy, 
  PieChart, 
  Refresh,
  Edit,
  Upload,
  Download
} from '@element-plus/icons-vue'
import { getAllCourses } from '@/api/course'
import { getCourseSelections, updateGrade } from '@/api/selection'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()
const loading = ref(false)
const courses = ref([])

const studentDialog = reactive({
  visible: false,
  title: '',
  course: null,
  students: [],
  loading: false
})

const gradeDialog = reactive({
  visible: false,
  title: '',
  course: null,
  students: [],
  loading: false
})

const batchGradeDialog = reactive({
  visible: false
})

const batchGradeForm = reactive({
  grade: null,
  applyTo: ['ungraded']
})

// 统计信息
const stats = computed(() => {
  const totalCourses = courses.value.length
  const totalStudents = courses.value.reduce((sum, course) => sum + (course.current_enrollment || 0), 0)
  const totalCredits = courses.value.reduce((sum, course) => sum + (course.credit || 0), 0)
  const totalCapacity = courses.value.reduce((sum, course) => sum + (course.capacity || 0), 0)
  const averageEnrollment = totalCapacity > 0 
    ? Math.round((totalStudents / totalCapacity) * 100)
    : 0

  return {
    totalCourses,
    totalStudents,
    totalCredits,
    averageEnrollment
  }
})

// 计算选课进度百分比
const getEnrollmentPercentage = (course) => {
  if (!course.capacity || course.capacity === 0) return 0
  return Math.round((course.current_enrollment || 0) / course.capacity * 100)
}

// 获取状态类型
const getStatusType = (course) => {
  const current = course.current_enrollment || 0
  if (current >= course.capacity) return 'danger'
  if (current / course.capacity > 0.8) return 'warning'
  return 'success'
}

// 获取状态文本
const getStatusText = (course) => {
  const current = course.current_enrollment || 0
  if (current >= course.capacity) return '已满'
  if (current === 0) return '无人选择'
  return '正常'
}

// 获取学生状态类型
const getStudentStatusType = (status) => {
  switch (status) {
    case 'selected': return 'success'
    case 'completed': return 'info'
    case 'dropped': return 'danger'
    default: return ''
  }
}

// 获取学生状态文本
const getStudentStatusText = (status) => {
  switch (status) {
    case 'selected': return '在读'
    case 'completed': return '已完成'
    case 'dropped': return '已退课'
    default: return '未知'
  }
}

// 获取成绩类型
const getGradeType = (grade) => {
  const score = parseFloat(grade)
  if (score >= 90) return 'success'
  if (score >= 80) return ''
  if (score >= 70) return 'warning'
  if (score >= 60) return 'info'
  return 'danger'
}

// 获取成绩等级
const getGradeLevel = (grade) => {
  const score = parseFloat(grade)
  if (score >= 90) return 'A'
  if (score >= 80) return 'B'
  if (score >= 70) return 'C'
  if (score >= 60) return 'D'
  return 'F'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString()
}

// 获取教师课程列表
const fetchCourses = async () => {
  try {
    loading.value = true
    const response = await getAllCourses({ teacherId: authStore.user.id })
    if (response.code === 0) {
      courses.value = response.data.courses
    }
  } catch (error) {
    ElMessage.error('获取课程列表失败')
    console.error('获取课程列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查看学生列表
const handleViewStudents = async (course) => {
  studentDialog.course = course
  studentDialog.title = `${course.name} - 学生列表`
  studentDialog.visible = true
  studentDialog.loading = true

  try {
    const response = await getCourseSelections({ courseId: course.id })
    if (response.code === 0) {
      studentDialog.students = response.data.selections
    }
  } catch (error) {
    ElMessage.error('获取学生列表失败')
    console.error('获取学生列表失败:', error)
  } finally {
    studentDialog.loading = false
  }
}

// 成绩管理
const handleGradeManagement = async (course) => {
  gradeDialog.course = course
  gradeDialog.title = `${course.name} - 成绩管理`
  gradeDialog.visible = true
  gradeDialog.loading = true

  try {
    const response = await getCourseSelections({ courseId: course.id })
    if (response.code === 0) {
      gradeDialog.students = response.data.selections.map(student => ({
        ...student,
        gradeChanged: false,
        originalGrade: student.grade
      }))
    }
  } catch (error) {
    ElMessage.error('获取学生列表失败')
    console.error('获取学生列表失败:', error)
  } finally {
    gradeDialog.loading = false
  }
}

// 成绩变更处理
const handleGradeChange = (student) => {
  student.gradeChanged = student.grade !== student.originalGrade
}

// 保存单个成绩
const handleSaveGrade = async (student) => {
  try {
    const response = await updateGrade({
      selectionId: student.id,
      grade: student.grade
    })
    
    if (response.code === 0) {
      ElMessage.success('成绩保存成功')
      student.gradeChanged = false
      student.originalGrade = student.grade
    }
  } catch (error) {
    ElMessage.error('保存成绩失败')
    console.error('保存成绩失败:', error)
  }
}

// 保存所有成绩
const handleSaveAllGrades = async () => {
  const changedStudents = gradeDialog.students.filter(s => s.gradeChanged)
  
  if (changedStudents.length === 0) {
    ElMessage.info('没有需要保存的成绩')
    return
  }

  try {
    const promises = changedStudents.map(student => 
      updateGrade({
        selectionId: student.id,
        grade: student.grade
      })
    )

    await Promise.all(promises)
    ElMessage.success(`成功保存 ${changedStudents.length} 个学生的成绩`)
    
    // 重置状态
    changedStudents.forEach(student => {
      student.gradeChanged = false
      student.originalGrade = student.grade
    })
  } catch (error) {
    ElMessage.error('批量保存成绩失败')
    console.error('批量保存成绩失败:', error)
  }
}

// 批量录入成绩
const handleBatchGrade = () => {
  batchGradeForm.grade = null
  batchGradeForm.applyTo = ['ungraded']
  batchGradeDialog.visible = true
}

// 确认批量录入
const handleConfirmBatchGrade = () => {
  if (!batchGradeForm.grade) {
    ElMessage.warning('请输入成绩')
    return
  }

  const applyToAll = batchGradeForm.applyTo.includes('all')
  const applyToUngraded = batchGradeForm.applyTo.includes('ungraded')

  gradeDialog.students.forEach(student => {
    const shouldApply = applyToAll || (applyToUngraded && !student.originalGrade)
    if (shouldApply) {
      student.grade = batchGradeForm.grade
      student.gradeChanged = student.grade !== student.originalGrade
    }
  })

  batchGradeDialog.visible = false
  ElMessage.success('批量设置成绩完成')
}

// 导入成绩
const handleImportGrades = () => {
  ElMessage.info('导入成绩功能开发中...')
}

// 导出成绩
const handleExportGrades = () => {
  ElMessage.info('导出成绩功能开发中...')
}

// 导出学生名单
const handleExportStudentList = () => {
  ElMessage.info('导出名单功能开发中...')
}

// 行点击处理
const handleRowClick = (row) => {
  handleViewStudents(row)
}

// 刷新
const handleRefresh = () => {
  fetchCourses()
}

onMounted(() => {
  fetchCourses()
})
</script>

<style scoped>
.teacher-courses {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #909399;
  margin: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 20px;
  color: white;
}

.stat-icon.courses {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.students {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-icon.credits {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.capacity {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-info h3 {
  font-size: 24px;
  color: #303133;
  margin: 0 0 4px 0;
  font-weight: 600;
}

.stat-info p {
  color: #909399;
  margin: 0;
  font-size: 14px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-info .course-name {
  font-weight: 500;
  color: #303133;
}

.course-info .course-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.enrollment-info {
  font-size: 12px;
  color: #606266;
}

.no-grade {
  color: #c0c4cc;
  font-size: 12px;
}

.grade-management {
  padding: 10px 0;
}

.grade-actions {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-input-number) {
  width: 120px;
}

:deep(.el-progress-bar__inner) {
  transition: width 0.3s ease;
}
</style> 